package com.jilian.powerstation.modul.natives;

import android.app.Dialog;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseActivity;
import com.jilian.powerstation.common.dto.AdvanceSettingDto;
import com.jilian.powerstation.common.event.MessageEvent;
import com.jilian.powerstation.dialog.nicedialog.BaseNiceDialog;
import com.jilian.powerstation.dialog.nicedialog.NiceDialog;
import com.jilian.powerstation.dialog.nicedialog.ViewConvertListener;
import com.jilian.powerstation.dialog.nicedialog.ViewHolder;
import com.jilian.powerstation.http.SocketConfig;
import com.jilian.powerstation.http.SocketUtils;
import com.jilian.powerstation.utils.DataUtils;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.NumberUtils;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.rxjava.RxBus;
import com.jilian.powerstation.utils.rxjava.RxBusBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 手动操作设置
 */
public class ManualOperationActivity extends BaseActivity {
    private LinearLayout llOne;
    private TextView tv01;
    private RelativeLayout llTwo;
    private TextView tvTwo;
    private EditText tv02;
    private TextView tvRight;


    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_manual_operation;
    }

    @Override
    public void initView() {
        setNormalTitle("Manual operation setting", v -> finish());
        setrightTitle("Save", "#3298db", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manualSetting();
            }
        });

        llOne = (LinearLayout) findViewById(R.id.ll_one);
        tv01 = (TextView) findViewById(R.id.tv_01);
        llTwo = (RelativeLayout) findViewById(R.id.ll_two);
        tvTwo = (TextView) findViewById(R.id.tv_two);
        tv02 = (EditText) findViewById(R.id.tv_02);
        tvRight = (TextView) findViewById(R.id.tv_right);

    }
    private boolean isOne;
    private boolean isSetting;
    /**
     * 设置
     */
    private void manualSetting() {


        if (be == 3) {

            bad = Integer.parseInt(tv02.getText().toString());
        }
        if (be == 4) {
            jiuling = Integer.parseInt(tv02.getText().toString());
        }
        if (be == 5) {
            bac = Integer.parseInt(tv02.getText().toString()) * 10;
        }
          getLoadingDialog().showDialog();
        isSetting = true;
        RxTimerUtil.cancel();
        RxTimerUtil.timer(16000, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext() {
               if(isSetting){
                   getLoadingDialog().dismiss();
                   ToastUitl.showImageToastTips("Time timeout");
                   //SocketUtils.connectSocket();
               }
            }
        });

            if(be==3||be==4||be==5){
                //发设置命令
                setSetting();
            }
            else{
                setControll();
            }
    }
    /**
     * 发控制命令
     */
    private void setControll() {
        Log.e(TAG, "高级设置: 发送控制命令" );
        isOne = false;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("高级设置--工作模式", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.modeAdvanceSetting(be)));
                        SocketUtils.sendSerialPort(SocketConfig.modeAdvanceSetting(be));;

                    }
                }).start();

            }
        }, 10);

    }

    /**
     * 发设置命令
     */
    private void setSetting() {
        if(!TextUtils.isEmpty(tv02.getText().toString())){

            isOne = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG, "高级设置: 发送设置命令" );
                            if(be==3){
                                Log.e("高级设置--参数", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.manualSetting8D( bad)));
                                SocketUtils.sendSerialPort(SocketConfig.manualSetting8D(bad));
                            }
                            if(be==4){
                                Log.e("高级设置--参数", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.manualSetting90( jiuling)));
                                SocketUtils.sendSerialPort(SocketConfig.manualSetting90(jiuling));
                            }
                            if(be==5){
                                Log.e("高级设置--参数", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.manualSetting8C( bac)));
                                SocketUtils.sendSerialPort(SocketConfig.manualSetting8C(bac));
                            }

                        }
                    }).start();

                }
            }, 10);
        }
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        sandMessage();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
        EventBus.getDefault().unregister(this);
        RxTimerUtil.cancel();

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // 当按下返回键时所执行的命令
        if (keyCode == KeyEvent.KEYCODE_BACK&&isChange) {
            // 此处写你按返回键之后要执行的事件的逻辑
            showLeaveDialog();
            return false;

        }
        return super.onKeyDown(keyCode, event);

    }
    private boolean isChange;
    @Override
    public void initListener() {
        tv02.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange =  true;
            }
        });
        findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isChange){
                    showLeaveDialog();
                }
                else{
                    finish();
                }
            }
        });
        llOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVoltResponseModeDialog();
            }
        });
    }



    /**
     * 安规标准
     */
    private void showVoltResponseModeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_manual_operation_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);


                        TextView btnOne = (TextView) holder.getView(R.id.btn_one);
                        TextView btnTwo = (TextView) holder.getView(R.id.btn_two);
                        TextView btnThree = (TextView) holder.getView(R.id.btn_three);
                        TextView btnFour = (TextView) holder.getView(R.id.btn_four);


                        TextView btnCancel = (TextView) holder.getView(R.id.btn_cancel);

                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        btnOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                be = 0;
                                initSelect();
                            }
                        });
                        btnTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 3;
                                initSelect();

                            }
                        });

                        btnThree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 4;
                                initSelect();

                            }
                        });
                        btnFour.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 5;
                                initSelect();
                            }
                        });


                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private void initSelect()
    {
        switch (be){
            case 0:

                tv01.setText("SystemWaitMode");
                llTwo.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                be = 0;
                isChange = false;
                break;
            case 3:
                tv02.setFilters( new InputFilter[]{ new  InputFilter.LengthFilter( 4 )});
                tv01.setText("GridLossMode");
                llTwo.setVisibility(View.VISIBLE);
                tvTwo.setText("GridLossPower");
                tvRight.setVisibility(View.VISIBLE);
                tv02.setText(bad + "");
                tvRight.setText("W");
                be = 3;
                isChange = false;
                break;
            case 4:
                tv02.setFilters( new InputFilter[]{ new  InputFilter.LengthFilter( 4 )});
                llTwo.setVisibility(View.VISIBLE);
                tv01.setText("GridDisChrgMode");
                tvTwo.setText("GridDisChrgPower");
                tvRight.setVisibility(View.VISIBLE);
                tv02.setText(jiuling + "");
                tvRight.setText("W");
                be = 4;
                isChange = false;

                break;
            case 5:
                tv02.setFilters( new InputFilter[]{ new  InputFilter.LengthFilter( 3 )});
                llTwo.setVisibility(View.VISIBLE);
                tv01.setText("GridChrgMode");
                tvTwo.setText("GridChrgGrad");
                tvRight.setVisibility(View.VISIBLE);
                tv02.setText(bac/10 + "");
                tvRight.setText("%");

                be = 5;
                break;

        }
    }



    private boolean isGetData;
    private String errors[] = new String[]{"Configuration is complete", "After finishing the configuration, power down and restart the device.", "After finishing the configuration, restart in operating mode.", "Disable services for system configuration", "Unable to configure in transparent transmission upgrade", "Parameter out of range", "Parameter ID is not defined", "Parameter conflict, please check"};


    private int be,bac, bad, jiuling;

    private void initManualSetting(int bac, int bad, int jiuling) {

        isGetData = true;
        Log.e(TAG, "手动操作设置: " + be);
        Log.e(TAG, "手动操作设置: " + bad);
        Log.e(TAG, "手动操作设置: " + jiuling);
        Log.e(TAG, "手动操作设置: " + bac);
        this.bac = bac;
        this.bad = bad;
        this.jiuling = jiuling;
        initSelect();


    }


    private void sandMessage() {
        getLoadingDialog().show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("手动操作设置", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getMannualSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getMannualSetting());
                    }
                }).start();

            }
        }, 10);
    }

    private String tip;


    /**
     * 退出登录对话框
     */
    private void showTipsDialog(String msg) {

        isChange = false;
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText(msg);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * //监听外来是否要去成功的界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        /* Do something */
        if (EmptyUtils.isNotEmpty(event)
                && EmptyUtils.isNotEmpty(event.getSendMessage())

        ) {

            initSenMessage(event.getSendMessage());
        }
    }

    private void initSenMessage(RxBusBean.SendMessage sendMessage) {

        Log.e("手动操作设置", "all-我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
        /***车载终端控制查询**/
        if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SEARCH) {
            try {
                getLoadingDialog().dismiss();
                Log.e("手动操作设置", "我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
                Log.e("手动操作设置", "接受到的最原始的数据:" + DataUtils.ByteArrToHex(sendMessage.readContent));
                Log.e("手动操作设置", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");

                //int be = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                //Log.e("手动操作设置", "be: " + be);

                List<String> infoList = Arrays.asList(sendMessage.info);

                int bacIndex = infoList.indexOf("8C");
                int bac = DataUtils.HexToInt(sendMessage.info[bacIndex+2] + sendMessage.info[bacIndex+1]);
                // int bac = DataUtils.HexToInt(sendMessage.info[12] + sendMessage.info[11]);
                Log.e("手动操作设置", "8C: " + bac);


                int BADIndex = infoList.indexOf("8D");
                int bad = DataUtils.HexToInt(sendMessage.info[BADIndex+2] + sendMessage.info[BADIndex+1]);
                // int bad = DataUtils.HexToInt(sendMessage.info[15] + sendMessage.info[14]);
                Log.e("手动操作设置", "8D: " + bad);

                int JIULINIndex = infoList.indexOf("90");
                int jiuling = DataUtils.HexToInt(sendMessage.info[JIULINIndex+2] + sendMessage.info[JIULINIndex+1]);
                // int jiuling = DataUtils.HexToInt(sendMessage.info[18] + sendMessage.info[17]);
                Log.e("手动操作设置", "90: " + jiuling);

                initManualSetting(bac, bad, jiuling);
            }
            catch (Exception e){
                ToastUitl.showImageToastSuccess(e.getMessage()+" - ");
            }

        }

        //  设置命令
        else if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SETTING) {
            isSetting = false;
            getLoadingDialog().dismiss();
            String hexString = DataUtils.ByteArrToHex(sendMessage.readContent);
            Log.e(TAG, "手动操作设置总的数据:" + hexString);
            Log.e("手动操作设置配置命令", "我接收到了实时信息的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            Log.e("手动操作设置配置命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
            int result = DataUtils.HexToInt(sendMessage.info[6]);
            Log.e(TAG, "手动操作设置配置命令accept: "+result );

            //
            if (result == 0 || result == 1 || result == 2 || result == 3 || result == 4 || result == 6) {
                if(result==0){
                    //设置成功 就再去发控制命令
                    setControll();
                }
                else{
                    //设置失败就弹出错误
                    tip = errors[result];
                    showTipsDialog(tip);

                }

            } else
                {
                if (result == 5) {
                    // BB CA CF CB CC    0.01
                    int id = DataUtils.HexToInt(sendMessage.info[7]);
                    double min;
                    double max;
                    //16进制ID
                    String idStr = DataUtils.toHexString(id);
                    if (
                            "8c".equals(idStr)) {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]) * 0.1;
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]) * 0.1;

                    } else {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]);
                    }

                    if("8d".equals(idStr)){
                        tip = "GridLossPower is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("90".equals(idStr)){
                        tip = "GridDisChrgPower is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("8c".equals(idStr)){
                        tip = "GridChrgGrad is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }


//                   tip = "Parameter out of range，ID:" + idStr + "  value is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    showTipsDialog(tip);



                } else
                    {
                    tip = "System abnormal, error code is" + sendMessage.info[6];
                    showTipsDialog(tip);
                }
            }

        }

        //  控制命令 设置
        else if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.VEHICLE_MOUNTED) {
            isSetting = false;
            getLoadingDialog().dismiss();
            String hexString = DataUtils.ByteArrToHex(sendMessage.readContent);
            Log.e(TAG, "手动操作设置总的数据:" + hexString);
            Log.e("手动操作设置配置命令", "我接收到了实时信息的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            Log.e("手动操作设置配置命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
            if(sendMessage.readContent[3] ==SocketConfig.SUCCESS){
                tip = errors[0];
                showTipsDialog(tip);

            }



        }


    }


}
